/**
 * Created by ${PRODUCT_NAME}.
 * User: skylerparr
 * Date: 1/9/11
 * Time: 10:53 AM
 * To change this template use File | Settings | File Templates.
 */
package com.thoughtorigin.meta {
import com.thoughtorigin.meta.ViewComponent;
import com.thoughtorigin.meta.*;
import com.thoughtorigin.application.Disposable;
import com.thoughtorigin.reflect.MetaDataItem;

import flash.display.DisplayObject;
import flash.events.Event;
import flash.events.IEventDispatcher;
import flash.utils.Dictionary;

public class DestructorMetaData implements MetaType {

    public function DestructorMetaData() {
    }

    public function decorate(object:Object, metadata:MetaDataItem, callback:Function):void {
        if(object is ViewComponent) {
            ViewComponent(object).view.addEventListener(Event.REMOVED_FROM_STAGE, dispose);
        }

        //todo: handle non display Object
        callback.call(this);
    }

    public function preprocess(clazz:Class, metadata:MetaDataItem):void {
    }

    public function get priority():int {
        return 19;
    }

    public function dispose(... args):void {
        var event: Event = args[0];
        var target: Object = event.target;
        if(target is Disposable) {
            Disposable(target).dispose();
        }
        IEventDispatcher(target).removeEventListener(Event.REMOVED_FROM_STAGE, dispose);
    }
}
}
